SpringBoot怎么整合WebSocket实现后端向前端发送消息 您所在的位置:网站首页 springboot websocket 心跳 SpringBoot怎么整合WebSocket实现后端向前端发送消息

SpringBoot怎么整合WebSocket实现后端向前端发送消息

2023-05-16 06:01| 来源: 网络整理| 查看: 265

一、什么是 websocket 接口

使用 websocket 建立长连接,服务端和客户端可以互相通信,服务端只要有数据更新,就可以主动推给客户端。

WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

二、适用场景

在业务开发过程中碰到一些异步处理(微信支付、支付宝支付的支付通知),跨应用的消息传递。

当业务执行完毕后,需要将成功的信息投递给前端。一般情况下都是前端调用后端的http/https接口获取数据,后端想要主动推送消息给前端就需要使用到WebSocket进行前后端的通信。

三、示例代码3.1、添加pom.xml依赖 org.springframework.boot spring-boot-starter-websocket 登录后复制3.2、创建WebSokcet配置类@Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } } 3.3、创建WebSokcet工具类 @ServerEndpoint(value = "/websocket") @Component public class WebSocketServer { private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class); //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; /** * 连接建立成功调用的方法 */ @OnOpen public void onOpen(Session session) { this.session = session; //加入set中 webSocketSet.add(this); //在线数加1 addOnlineCount(); log.info("有新连接加入!当前在线人数为" + getOnlineCount()); try { MsgResponseVo userMsgResponseVo = new MsgResponseVo(); userMsgResponseVo.setMsg("SUCCESS"); WebSocketServer.sendInfo(JSON.toJSONString(userMsgResponseVo)); } catch (IOException e) { log.error("websocket IO异常"); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { //从set中删除 webSocketSet.remove(this); //在线数减1 subOnlineCount(); log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info("来自客户端的消息:" + message); //群发消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } /** * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 群发自定义消息 */ public static void sendInfo(String message) throws IOException { log.info(message); for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { continue; } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }登录后复制3.3、创建测试发送消息接口 @GetMapping("/testWebSocket") public ApiRestResponse testWebSocket() throws IOException { //消息体 MsgResponseVo technicianMsgResponseVo = new MsgResponseVo(); technicianMsgResponseVo.setRole("Technician"); technicianMsgResponseVo.setRoleId(1); technicianMsgResponseVo.setMsg("您的订单已取消"); technicianMsgResponseVo.setMsgStatus("CANCEL_ORDER"); technicianMsgResponseVo.setOrderNo("test"); //发送消息 WebSocketServer.sendInfo(JSON.toJSONString(technicianMsgResponseVo)); return ApiRestResponse.success(); } }登录后复制3.4、测试webSocket

在网站中输入ws://ip:端口/webSocket工具类的前缀(ws://127.0.0.1:8080/websocket)

SpringBoot怎么整合WebSocket实现后端向前端发送消息

3.5、前端使用WebSocket监听后端WebSocket地址 ,接收到消息后做下一步业务处理。

以上就是SpringBoot怎么整合WebSocket实现后端向前端发送消息的详细内容,更多请关注php中文网其它相关文章!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有